import { $wuxLoading } from '../components/wux';
import judge from "judge.js";


function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}

function formatDate(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1
  var day = date.getDate()

  return [year, month, day].map(formatNumber).join('-');
}

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatAudioLength(audioLength){
  var hour=parseInt(audioLength/(60*60));
  var remainTime=audioLength-hour*60*60;

  var minute=parseInt(remainTime/60);
  remainTime=remainTime-minute*60;
  if(hour>0){
    return [hour,minute,remainTime].map(formatNumber).join(":");
  }else {
    return [minute,remainTime].map(formatNumber).join(":");
  }
}

/**
 * 格式化剩余时间
 * params remaindTime 毫秒
 */
function formatRemaindTime(remaindTime){
  var day=parseInt(remaindTime/(1000*60*60*24));
  remaindTime=remaindTime-day*1000*60*60*24;
  var hour=parseInt(remaindTime/(1000*60*60));
  remaindTime=remaindTime-hour*1000*60*60;
  var minute=parseInt(remaindTime/(1000*60));
  remaindTime=remaindTime-minute*1000*60;

  if(day!=0){
    return day+"天"+hour+"小时"+minute+"分"+remaindTime+"秒";
  }
  if(hour>0){
    return hour+"小时"+minute+"分"+remaindTime+"秒";
  }
  if(minute>0){
    return minute+"分"+remaindTime+"秒";
  }
  return remaindTime+"秒";
}

/**
 * 把一个一维数组转换成二维数组
 * param arrayData 一维数组
 * param sliceLength 每个小数组的长度 
 */
function arrayToDoubleArray(arrayData,sliceLength){
  var newArr = new Array();

    if (arrayData == undefined){
        return newArr;
    }
  var subArr=null;
  for(var i =0;i<arrayData.length;i++){
    if((i%sliceLength==0) ||subArr==null){
      subArr = new Array();
      newArr.push(subArr);
    }
    subArr.push(arrayData[i]);
  }
  return newArr;
}


/**
 *
 * @param arr
 * @param num
 */
function to2DimensionArr(arr,num){
    var newArr = new Array();//二维数组

    if (arr == undefined){
        return newArr;
    }
    var subArr=null;
    for(var i =0;i<arr.length;i++){
        var item = arr[i];
        if((i%num==0) ||subArr==null){
            subArr = new Array();//内部的一维数组
            newArr.push(subArr);
        }
        subArr.push(item);
    }
    return newArr;


}

function log(msg){
    var isDebug = getApp().globalData.isDebug;
    if (isDebug){
        console.log(msg);
    }
}
 
function refreshUI(that){
    that.setData(that.data);

}

function isAdmin(app){
    if(app.globalData.user.uid ==44 || app.globalData.user.uid == 45){
        return true;
    }
    return false;
}

function getsid(){
 return wx.getStorageSync('sid')
}

function getiv() {
  return wx.getStorageSync('iv')
}

function getkey(){
  return wx.getStorageSync('key')
}

function alert(s,fn){
   if(s==undefined){
    s ="不能定位错误提示";
   }
   s = s.toString();
   var obj = {
    title: '消息提示',
    content: s
    ,showCancel:false
   }
   if(fn){
    obj.success =fn;
   }
   wx.showModal(obj);
}

function confirm(s,fn){
    if(s==undefined){
        s ="不能定位错误提示";
    }
    s = s.toString();
    var obj = {
        title: '消息提示',
        content: s
     ,showCancel:true
    }
    if(fn){
        obj.success =fn;
    }
    wx.showModal(obj);
}

function showToast(s){
  if(s==undefined){
    s ="";
   }
	wx.showToast({
      title: s
	})
}

function hideToast(){
  
   wx.hideToast();
}

function showLoading(){
  //  wx.showLoading({
  //   title: '加载中'
  // });
  $wuxLoading.show({
      text: '加载中',
    })
}

function hideLoading(){
   // wx.hideLoading();
  $wuxLoading.hide()
}


Promise.stop = function(){
  return new this();
}

function stop(ob){
  // return Promise.stop();
    if(ob){
        return ob;
    }
    return {};
}

function toobj(s){
  var data=JSON.parse(s);
  return data;
}

function alert_catch(res){
    if(this.judge.isObject(res) && res.hasOwnProperty("message") && res.message){
        this.alert(res.message,function(){
            wx.redirectTo({
                url: '../index/error'
            });
        });
    }
    else if(this.judge.isObject(res) && res.hasOwnProperty("errMsg") && res.errMsg){
        this.alert(res.errMsg,function(){
            // wx.redirectTo({
                // url: '../index/error'
            // });
        });
    }
    else{
        if(this.judge.isString(res)){
            this.alert(res);
        }
    }
}

 /** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
    可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
    Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423      
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04      
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04      
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04      
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18      
 */  
function date2str(date,fmt) {    
    if (date == undefined){ 
      date = new Date() 
    } 

    if (judge.isString(date)){ 
      if (date == "") { date = new Date() } 
      else { date = new Date(date.replace(/-/g, "/").replace(/T/g, "/")) } 
    }

    var o = {         
    "M+" : date.getMonth()+1, //月份         
    "d+" : date.getDate(), //日         
    "h+" : date.getHours()%12 == 0 ? 12 : date.getHours()%12, //小时         
    "H+" : date.getHours(), //小时         
    "m+" : date.getMinutes(), //分         
    "s+" : date.getSeconds(), //秒         
    "q+" : Math.floor((date.getMonth()+3)/3), //季度         
    "S" : date.getMilliseconds() //毫秒         
    };         
    var week = {         
    "0" : "/u65e5",         
    "1" : "/u4e00",         
    "2" : "/u4e8c",         
    "3" : "/u4e09",         
    "4" : "/u56db",         
    "5" : "/u4e94",         
    "6" : "/u516d"        
    };         
    if(/(y+)/.test(fmt)){         
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));         
    }         
    if(/(E+)/.test(fmt)){         
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);         
    }         
    for(var k in o){         
        if(new RegExp("("+ k +")").test(fmt)){         
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         
        }         
    }         
    return fmt;         
}  

function str2date(date) { 
  if (date == "") { date = new Date() } 
  else { date = new Date(date.replace(/-/g, "/").replace(/T/g, "/")) } 
    return date;
}

function objtostr(obj){
  var data = JSON.stringify(obj);
  return data;
}

module.exports = {
  json2Form: json2Form
  ,formatTime: formatTime
  ,formatDate: formatDate
  ,formatRemaindTime:formatRemaindTime
  ,formatAudioLength:formatAudioLength
  ,arrayToDoubleArray:arrayToDoubleArray
  ,refreshUI:refreshUI
  ,to2DimensionArr:to2DimensionArr
  ,getsid:getsid
  ,getkey:getkey
  ,getiv: getiv
  ,alert: alert
  ,hideToast: hideToast
  ,showToast: showToast
  ,showLoading: showLoading
  ,hideLoading: hideLoading
  ,stop:stop
  ,toobj:toobj
  ,alert_catch:alert_catch
  ,'judge':judge
  ,date2str:date2str
  ,str2date:str2date
    ,confirm:confirm
    ,isAdmin:isAdmin
  ,objtostr:objtostr
}

